package nl.saxion.ein4b.model;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

import android.content.Context;

/**
 * Manager class to load/save profiles to internal storage of the android device
 * 
 * @author Jaap
 * 
 */
public class ProfileManager implements Serializable {
	FileOutputStream fos;
	FileInputStream fis;
	ArrayList<Profile> profiles;
	String FILENAME = "profiles.dat";
	Context c;

	public ProfileManager(Context c) {
		this.c = c;
		profiles = new ArrayList<Profile>();
		try {
			fis = c.openFileInput(FILENAME);
		} catch (Exception e) {
			e.printStackTrace();
		}
		load();
		try {
			fos = c.openFileOutput(FILENAME, Context.MODE_PRIVATE);
			save();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Load profiles form disk
	 */
	public ArrayList<Profile> loadProfiles() {
		// load();
		return profiles;
	}

	/**
	 * Save a profile to disk
	 */
	public void saveProfile(Profile p) {
		profiles.set(getProfileIndex(p), p);
		save();
	}

	/**
	 * Save a new profile to disk
	 */
	public void newProfile(Profile p) {
		profiles.add(p);
		save();
	}

	public Profile getProfile(String name) {
		name = name.split("    Coins:")[0];
		System.out.println(name);
		System.out.println(getProfileIndex(name));
		System.out.println(profiles.size());
		Profile p = profiles.get(getProfileIndex(name));
		return p;
	}

	public void save() {
		System.out.println("saving profiles");
		try {
			// profiles.add(new Profile("Henk","",100,0));
			String string = "";
			profiles.trimToSize();
			for (Profile p : profiles) {
				string += "," + p.getName() + "~" + p.getPicture() + "~"
						+ p.getCredit() + "~" + p.getNumGamesPlayed();
			}
			try {
				c.deleteFile(FILENAME);
				fos = c.openFileOutput(FILENAME, Context.MODE_PRIVATE);
			} catch (Exception ex) {
				// ex.printStackTrace();
			}
			fos.write(string.getBytes());
		} catch (Exception e) {
			// e.printStackTrace();
		}
	}

	public void load() {
		System.out.println("loading profiles");
		try {
			profiles = new ArrayList<Profile>();
			int ch;
			StringBuffer strContent = new StringBuffer("");
			while ((ch = fis.read()) != -1)
				strContent.append((char) ch);
			String[] profs = strContent.toString().split(",");
			for (String s : profs) {
				String[] values = s.split("~");
				if (values.length == 4)
					profiles.add(new Profile(values[0], values[1], Integer
							.parseInt(values[2]), Integer.parseInt(values[3])));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int getProfileIndex(Profile p) {
		int i = 0;
		for (Profile q : profiles) {
			if (q.getName().equals(p.getName())) {
				return i;
			}
			i++;
		}
		return -1;
	}

	public int getProfileIndex(String name) {
		int i = 0;
		for (Profile q : profiles) {
			if (q.getName().equals(name)) {
				return i;
			}
			i++;
		}
		return -1;
	}

	public Object toObject(byte[] bytes) {
		Object obj = null;
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bis);
			obj = ois.readObject();
		} catch (IOException ex) {
			// TODO: Handle the exception
		} catch (ClassNotFoundException ex) {
			// TODO: Handle the exception
		}
		return obj;
	}

	public byte[] toByteArray(Object obj) {
		byte[] bytes = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(obj);
			oos.flush();
			oos.close();
			bos.close();
			bytes = bos.toByteArray();
		} catch (Exception e) {
			// TODO: Handle the exception
		}
		return bytes;
	}
}
